package cron

import (
	"bigdevops/src/models"
	"context"
	"go.uber.org/zap"
)

// renew map方式

func (ac *AlertCache) RenewMapUser(ctx context.Context) {

	// 先从数据库中查询出所有
	users, err := models.GetUserAll()
	if err != nil {
		ac.Sc.Logger.Error("[缓存刷新模块]扫描数据库中的users失败",
			zap.Error(err),
		)
		return
	}
	if len(users) == 0 {
		return
	}

	tmpM := map[uint]*models.User{}
	for _, user := range users {
		user := user
		tmpM[user.ID] = user
	}

	// 模拟 数据量很大，刷新缓存很慢
	//time.Sleep(30 * time.Second)

	ac.UserLock.Lock()
	lastNum := len(ac.SendGroupMap)
	ac.UserMap = tmpM
	thiNum := len(ac.SendGroupMap)

	ac.UserLock.Unlock()
	ac.Sc.Logger.Info("RenewMapUser 刷新缓存结果....",
		zap.Any("上一次数量", lastNum),
		zap.Any("这一次数量", thiNum),
	)

}

func (ac *AlertCache) GetUserById(id uint) *models.User {

	ac.UserLock.RLock()
	defer ac.UserLock.RUnlock()
	return ac.UserMap[id]
}
